/* 局部引入的工具类 */
import Store from '@/store';
import VUE from 'vue'
import Config from '@/config/config.conf';
import API from '@/api/index.js';

function createCaptcha(context, width, height, captcha) {
  // 初始化验证码, captcha存在则指定验证码内容
  // let context = uni.createCanvasContext('imgcanvas', this)
  let w = width / 750 * uni.getSystemInfoSync().screenWidth;
  let h = height;
  context.setFillStyle("white");
  context.setLineWidth(5);
  context.fillRect(0, 0, w, h);
  let pool = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "I", "M", "N", "O", "P", "Q", "R", "S",
      "T", "U", "V", "W", "S", "Y", "Z", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0"
    ],
    str = '';
  for (let i = 0; i < 4; i++) {
    // 构造字符串
    let c = captcha ? captcha.charAt(i) : pool[rn(0, pool.length - 1)];

    let deg = rn(-30, 30);
    context.setFontSize(18);
    context.setTextBaseline("top");
    context.setFillStyle(rc(80, 150));
    context.save();
    context.translate(30 * i + 15, parseInt(h / 1.5));
    context.rotate(deg * Math.PI / 180);
    context.fillText(c, -15 + 5, -15);
    context.restore();
    str += c;
  }
  for (let i = 0; i < 40; i++) {
    // 模糊背景
    context.beginPath();
    context.arc(rn(0, w), rn(0, h), 1, 0, 2 * Math.PI);
    context.closePath();
    context.setFillStyle(rc(150, 200));
    context.fill();
  }
  context.draw();
}

/**
 * 判断是否微信浏览器环境
 * */
function isWeChat() {
  const ua = navigator.userAgent.toLowerCase();
  const isWeixin = ua.indexOf('micromessenger') != -1;
  return isWeixin ? true : false;
}


function getUserInfo(e, type) { // type = login说明是需要登录才能访问的接口
  // 每个页面首次进入，判断初始化
  return new Promise((resolve, reject) => {
    if (type === 'login') {
      let token = uni.getStorageSync('token');
      if (process.env.NODE_ENV === 'development') {
        // 测试环境默认显示页面
        Store.state.user.showPage = true
        // uni.setStorageSync('token', '8115788e-dcba-4858-ad40-8d01af7cb551') // 大号token_dev
        // return
      }
      // 初始化OSS信息
      API.common.initSystem({
        version: Config.version
      }).then(res => {
        if (!Store.state.system.ossLink) {
          Store.state.system.ossLink = res.data.uploaddata.cdnurl
          Store.state.system.uploadApi = res.data.uploaddata.uploadurl
        }
        API.user.getUserInfo().then(res => {
          // 调用用户信息接口
          Store.state.user.userInfo = {
            ...res.data.row,
          }
          let routes = VUE.prototype.$utils.getRoute()
          if ((res.data.row.nickname && res.data.row.mobile) || routes.path.indexOf(
              'pages/user/register/index') !== -1 || routes.path.indexOf('pages/user/uesr-center/index') !==
            -1 || routes.path.indexOf('pages/user/profile/index') !==
            -1) {
            Store.state.user.showPage = true
            resolve('true')
          } else {
            // 未完善资料
            uni.setStorageSync('originPage', routes.path + '?' + routes.param) // 存储登陆前页面
            uni.redirectTo({
              url: '/pages/user/register/index'
            });
            reject('fail')
          }

        })

      })
    } else {
      // 无需登录的页面
      if (process.env.NODE_ENV === 'development') {
        // 测试环境默认显示页面
        Store.state.user.showPage = true
        // uni.setStorageSync('token', '8115788e-dcba-4858-ad40-8d01af7cb551') // 大号token_dev
        // return
      }
      // 初始化OSS信息
      API.common.initSystem({
        version: Config.version
      }).then(res => {
        Store.state.system.ossLink = res.data.uploaddata.cdnurl
        Store.state.system.uploadApi = res.data.uploaddata.uploadurl
        Store.state.user.showPage = true
        resolve('true')
      })
    }

  })
}

function rc(min, max) {
  // 创建验证码需要
  let r = rn(min, max);
  let g = rn(min, max);
  let b = rn(min, max);
  return `rgb(${r},${g},${b})`
}

function rn(max, min) {
  // 创建验证码需要
  return parseInt(Math.random() * (max - min)) + min;
}

/* 全局引入的工具类 */
function phone(phone) {
  // 打电话功能
  if (!phone) {
    uni.showToast({
      icon: 'none',
      title: '电话不存在'
    });
    return;
  }
  uni.makePhoneCall({
    phoneNumber: phone
  });
}

function copy(text) {
  // 跨端复制功能
  // #ifdef H5
  const btn = document.querySelector('.copy_tkl');
  const input = document.createElement('input');
  input.setAttribute('readonly', 'readonly');
  input.setAttribute('value', text);
  document.body.appendChild(input);
  input.select();
  input.setSelectionRange(0, 9999);
  if (document.execCommand('copy')) {
    document.execCommand('copy');
    uni.showToast({
      title: '复制成功'
    });
  }
  document.body.removeChild(input);
  // #endif
  // #ifndef H5
  uni.setClipboardData({
    data: text,
    success: () => {
      uni.showToast({
        title: '复制成功'
      });
    }
  });
  // #endif
}

function getRoute() {
  let pages = getCurrentPages();
  let routes = getCurrentPages(); // 获取当前打开过的页面路由数组
  let curRoute = routes[routes.length - 1].route; //获取当前页面路由
  let curParam = routes[routes.length - 1].options; //获取路由参数
  // 拼接参数
  let param = '';
  for (let key in curParam) {
    if (param === '') {
      param += key + '=' + curParam[key];
    } else {
      param += '&' + key + '=' + curParam[key];
    }
  }
  let route = {
    path: curRoute, // 页面路径，开头不带/      pages/index/index
    param: param, // 页面参数，如a=1&b=2
  }
  return route
}

/*
 *获取当前URL中的指定参数
 */
function GetQueryString(name) {
  var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
  var r = window.location.search.substr(1).match(reg);
  if (r != null) {
    return unescape(r[2]);
  }
  return null;
};

//替换指定传入URL参数的值,paramName为参数,replaceWith为新值
function replaceParamVal(href, paramName, replaceWith) {
  var oUrl = href;
  var re = eval('/(' + paramName + '=)([^&]*)/gi');
  var nUrl = oUrl.replace(re, paramName + '=' + replaceWith);
  this.location = nUrl;
  return nUrl
}

// 单个文件上传工具类
async function UploadFile(file, channelId) {
  return new Promise((resolve, reject) => {
    uni.uploadFile({
      url: (process.env.NODE_ENV === 'development' ? 'http://zsgh.center999.com/' : Config.domain) +
        'api/common/nupload',
      filePath: file,
      name: 'file',
      formData: {
        channelId: channelId || ''
      },
      header: {},
      success: (res) => {
        if (res.statusCode == 200) {
          if (JSON.parse(res.data).code === 0) {
            uni.showToast({
              icon: 'none',
              title: JSON.parse(res.data).msg || '文件上传失败'
            })
            reject(res || 'false')
          } else {
            resolve(JSON.parse(res.data))
          }
        }
      },
      fail: (err) => {
        reject(err || 'false')
      }
    })
  })
}


function getCurrentDate(timestamp) {
  // 获取当前时间的各个参数值
  let date = null;
  if (timestamp) {
    date = new Date(timestamp);
  } else {
    date = new Date();
  }
  return {
    year: date.getFullYear(),
    month: date.getMonth() + 1,
    day: date.getDate(),
    date: `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`
  }
}


//递归删除空数组
function removeNummArray(arr, param) {
  arr.forEach(item => {
    if (item[param] && item[param].length > 0) {
      this.removeNummArray(item[param], param)
    } else {
      delete item[param]
    }
  })
  return arr
}

export default {
  createCaptcha,
  copy,
  getRoute,
  isWeChat,
  getUserInfo,
  phone,
  GetQueryString,
  replaceParamVal,
  UploadFile,
  getCurrentDate,
  removeNummArray,
}
